using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Common;
using WPF_MVVM_Test.MVVM_Model.ProductionOrder;
using WPF_MVVM_Test.MVVM_Services;

namespace WPF_MVVM_Test.MVVM_ViewModel.ProductionOrder
{
    public class ProductionOrderViewModel : BaseViewModel
    {
        private readonly ProductionOrderService _productionOrderService;
        private bool _isLoading;

        public ProductionOrderViewModel()
        {
            _productionOrderService = new ProductionOrderService();
            
            // 初始化命令
            InitializeCommands();
            
            // 初始化数据
            InitializeData();
            
            // 加载数据
            _ = LoadProductionOrdersAsync();
        }

        #region 属性

        public ObservableCollection<ProductionOrderModel> ProductionOrders { get; set; } = new ObservableCollection<ProductionOrderModel>();

        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        // 分页属性
        private int _currentPage = 1;
        private int _pageSize = 10;
        private int _totalCount = 0;
        private int _totalPages = 0;
        private string _goToPage = "1";

        public int CurrentPage
        {
            get => _currentPage;
            set => SetProperty(ref _currentPage, value);
        }

        public int PageSize
        {
            get => _pageSize;
            set
            {
                if (SetProperty(ref _pageSize, value))
                {
                    CurrentPage = 1; // 重置到第一页
                    _ = LoadProductionOrdersAsync();
                }
            }
        }

        public int TotalCount
        {
            get => _totalCount;
            set => SetProperty(ref _totalCount, value);
        }

        public int TotalPages
        {
            get => _totalPages;
            set => SetProperty(ref _totalPages, value);
        }

        public string GoToPage
        {
            get => _goToPage;
            set => SetProperty(ref _goToPage, value);
        }

        public string PageInfo => $"共{TotalCount}条";

        // 搜索属性
        private string _searchOrderNumber = "";
        private string _searchProductName = "";
        private string _searchStatus = "";

        public string SearchOrderNumber
        {
            get => _searchOrderNumber;
            set => SetProperty(ref _searchOrderNumber, value);
        }

        public string SearchProductName
        {
            get => _searchProductName;
            set => SetProperty(ref _searchProductName, value);
        }

        public string SearchStatus
        {
            get => _searchStatus;
            set => SetProperty(ref _searchStatus, value);
        }

        // 选项列表
        public List<int> PageSizeOptions { get; } = new List<int> { 5, 10, 20, 50, 100 };
        public List<string> StatusOptions { get; } = new List<string> { "待排产", "未开始", "进行中", "已完成", "已暂停", "已关闭" };

        #endregion

        #region 命令

        public ICommand LoadDataCommand { get; private set; }
        public ICommand PreviousPageCommand { get; private set; }
        public ICommand NextPageCommand { get; private set; }
        public ICommand GoToPageCommand { get; private set; }
        public ICommand SearchCommand { get; private set; }
        public ICommand ResetSearchCommand { get; private set; }
        public ICommand StartSelectedCommand { get; private set; }
        public ICommand CancelSelectedCommand { get; private set; }
        public ICommand EndSelectedCommand { get; private set; }
        public ICommand RecallSelectedCommand { get; private set; }
        public ICommand ScheduleProductionCommand { get; private set; }
        public ICommand ViewProductionCommand { get; private set; }
        public ICommand RefreshCommand { get; private set; }

        #endregion

        #region 初始化方法

        private void InitializeCommands()
        {
            LoadDataCommand = new RelayCommand(async () => await LoadProductionOrdersAsync());
            PreviousPageCommand = new RelayCommand(PreviousPage, CanPreviousPage);
            NextPageCommand = new RelayCommand(NextPage, CanNextPage);
            GoToPageCommand = new RelayCommand(GoToSpecificPage);
            SearchCommand = new RelayCommand(async () => await LoadProductionOrdersAsync());
            ResetSearchCommand = new RelayCommand(ResetSearch);
            
            StartSelectedCommand = new RelayCommand(async () => await StartSelectedProduction());
            CancelSelectedCommand = new RelayCommand(async () => await CancelSelectedProduction());
            EndSelectedCommand = new RelayCommand(async () => await EndSelectedProduction());
            RecallSelectedCommand = new RelayCommand(async () => await RecallSelectedProduction());
            
            ScheduleProductionCommand = new RelayCommand<ProductionOrderModel>(async (order) => await ScheduleProduction(order));
            ViewProductionCommand = new RelayCommand<ProductionOrderModel>(async (order) => await ViewProduction(order));
            RefreshCommand = new RelayCommand(async () => await RefreshDataAsync());
        }

        private void InitializeData()
        {
            // 初始化分页信息
            CurrentPage = 1;
            PageSize = 10;
            TotalCount = 0;
            TotalPages = 0;
        }

        #endregion

        #region 数据加载方法

        private async Task LoadProductionOrdersAsync()
        {
            try
            {
                IsLoading = true;

                var response = await _productionOrderService.GetProductionOrderListAsync(
                    SearchOrderNumber,
                    SearchProductName,
                    SearchStatus,
                    CurrentPage,
                    PageSize);

                if (response.IsSuc && response.Data != null)
                {
                    // 清空现有数据
                    ProductionOrders.Clear();

                    // 添加新数据并设置索引
                    for (int i = 0; i < response.Data.Data.Count; i++)
                    {
                        var order = response.Data.Data[i];
                        order.Index = (CurrentPage - 1) * PageSize + i + 1;
                    ProductionOrders.Add(order);
                }

                    // 更新分页信息
                    TotalCount = response.Data.TotalCount;
                    TotalPages = response.Data.TotalPage;
                }
                else
                {
                   /* MessageBox.Show($"加载数据失败: {response.Msg}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);*/
                }
            }
            catch (Exception ex)
            {
                /*MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);*/
            }
            finally
            {
                IsLoading = false;
            }
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private async Task RefreshDataAsync()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 开始刷新生产工单数据");
                
                // 显示加载状态
                IsLoading = true;
                
                // 重新加载数据
                await LoadProductionOrdersAsync();
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单数据刷新完成，共 {ProductionOrders.Count} 条记录");
                
                // 显示成功消息
                MessageBox.Show("数据刷新成功！", "刷新完成", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 刷新数据异常: {ex.Message}");
                MessageBox.Show($"刷新数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsLoading = false;
            }
        }

        #endregion

        #region 分页方法

        private void PreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                _ = LoadProductionOrdersAsync();
            }
        }

        private bool CanPreviousPage()
        {
            return CurrentPage > 1;
        }

        private void NextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                _ = LoadProductionOrdersAsync();
            }
        }

        private bool CanNextPage()
        {
            return CurrentPage < TotalPages;
        }

        private void GoToSpecificPage()
        {
            if (int.TryParse(GoToPage, out int page) && page >= 1 && page <= TotalPages)
            {
                CurrentPage = page;
                _ = LoadProductionOrdersAsync();
            }
            else
            {
                MessageBox.Show($"请输入有效的页码 (1-{TotalPages})", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                GoToPage = CurrentPage.ToString();
            }
        }

        #endregion

        #region 搜索方法

        private void ResetSearch()
        {
            SearchOrderNumber = "";
            SearchProductName = "";
            SearchStatus = "";
            CurrentPage = 1;
            _ = LoadProductionOrdersAsync();
        }

        #endregion

        #region 操作命令方法

        private async Task StartSelectedProduction()
        {
            var selectedOrders = ProductionOrders.Where(o => o.IsSelected).ToList();
            if (!selectedOrders.Any())
            {
                MessageBox.Show("请选择要开始的生产工单", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                foreach (var order in selectedOrders)
                {
                    var response = await _productionOrderService.StartProductionOrderAsync(order.Id);
                    if (!response.IsSuc)
                    {
                        MessageBox.Show($"开始工单 {order.OrderNumber} 失败: {response.Msg}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }

                // 重新加载数据
                await LoadProductionOrdersAsync();
                MessageBox.Show("操作完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task CancelSelectedProduction()
        {
            var selectedOrders = ProductionOrders.Where(o => o.IsSelected).ToList();
            if (!selectedOrders.Any())
            {
                MessageBox.Show("请选择要取消的生产工单", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var result = MessageBox.Show("确定要取消选中的生产工单吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    foreach (var order in selectedOrders)
                    {
                        var response = await _productionOrderService.CancelProductionOrderAsync(order.Id);
                        if (!response.IsSuc)
                        {
                            MessageBox.Show($"取消工单 {order.OrderNumber} 失败: {response.Msg}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }

                    await LoadProductionOrdersAsync();
                    MessageBox.Show("操作完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async Task EndSelectedProduction()
        {
            var selectedOrders = ProductionOrders.Where(o => o.IsSelected).ToList();
            if (!selectedOrders.Any())
            {
                MessageBox.Show("请选择要结束的生产工单", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var result = MessageBox.Show("确定要结束选中的生产工单吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    foreach (var order in selectedOrders)
                    {
                        var response = await _productionOrderService.EndProductionOrderAsync(order.Id);
                        if (!response.IsSuc)
                        {
                            MessageBox.Show($"结束工单 {order.OrderNumber} 失败: {response.Msg}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }

                    await LoadProductionOrdersAsync();
                    MessageBox.Show("操作完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async Task RecallSelectedProduction()
        {
            var selectedOrders = ProductionOrders.Where(o => o.IsSelected).ToList();
            if (!selectedOrders.Any())
            {
                MessageBox.Show("请选择要撤回的生产工单", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var result = MessageBox.Show("确定要撤回选中的生产工单吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    foreach (var order in selectedOrders)
                    {
                        var response = await _productionOrderService.RecallProductionOrderAsync(order.Id);
                        if (!response.IsSuc)
                        {
                            MessageBox.Show($"撤回工单 {order.OrderNumber} 失败: {response.Msg}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }

                    await LoadProductionOrdersAsync();
                    MessageBox.Show("操作完成", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private async Task ScheduleProduction(ProductionOrderModel order)
        {
            if (order == null) return;

            try
            {
                // 确认对话框
                var confirmResult = MessageBox.Show($"确定要为工单 {order.OrderNumber} 进行排产吗？", "排产确认",
                    MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (confirmResult != MessageBoxResult.Yes)
                {
                    return;
                }

                // 创建ViewModel
                ScheduleProductionDialogViewModel scheduleViewModel = null;
                try
                {
                    scheduleViewModel = new ScheduleProductionDialogViewModel(order);
                }
                catch (Exception vmEx)
                {
                    MessageBox.Show($"创建排产对话框失败：{vmEx.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 创建对话框
                WPF_MVVM_Test.MVVM_View.ProductionOrder.ScheduleProductionDialog dialog = null;
                try
                {
                    dialog = new WPF_MVVM_Test.MVVM_View.ProductionOrder.ScheduleProductionDialog(scheduleViewModel);
                }
                catch (Exception dialogEx)
                {
                    MessageBox.Show($"创建排产对话框失败：{dialogEx.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                // 设置父窗口
                try
                {
                    if (System.Windows.Application.Current.MainWindow != null)
                    {
                        dialog.Owner = System.Windows.Application.Current.MainWindow;
                    }
                }
                catch (Exception)
                {
                    // 设置父窗口失败不是致命错误，继续执行
                }

                // 显示对话框
                try
                {
                    var result = dialog.ShowDialog();

                    // 如果排产成功，刷新数据
                    if (result == true && scheduleViewModel.DialogResult)
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 排产成功，开始刷新生产工单数据");
                        
                        // 自动刷新生产工单列表
                        await LoadProductionOrdersAsync();
                        
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单数据刷新完成，共 {ProductionOrders.Count} 条记录");
                        
                        MessageBox.Show($"工单 {order.OrderNumber} 排产成功！数据已自动刷新。", "成功",
                            MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 排产操作被取消或失败");
                    }
                }
                catch (Exception showEx)
                {
                    MessageBox.Show($"显示排产对话框失败：{showEx.Message}", "错误",
                        MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"💥 排产操作异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"💥 堆栈跟踪: {ex.StackTrace}");
                MessageBox.Show($"打开排产对话框失败：{ex.Message}\n\n详细信息：{ex.StackTrace}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task ViewProduction(ProductionOrderModel order)
        {
            if (order == null) return;

            try
            {
                // 创建并显示工单详情对话框
                var detailDialog = new WPF_MVVM_Test.MVVM_View.ProductionOrder.ProductionOrderDetailDialog(order);
                
                // 设置父窗口
                if (System.Windows.Application.Current.MainWindow != null)
                {
                    detailDialog.Owner = System.Windows.Application.Current.MainWindow;
                }
                
                detailDialog.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开工单详情失败：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _productionOrderService?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
} 
